﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLibrary>
#include <QDebug>
#include "jlinkarm.h"
#include <QFileDialog>
#include <QTimer>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    timer = new QTimer(this);
    arm = new JlinkARM();
    if(!arm->jlinkIsOpen()) arm->jlinkOpen();
    qDebug()<<arm->jlinkIsOpen();
    arm->jlinkExecCommandFunc("device=S32K144",0,0);
    arm->jlinkTIFSelectFunc(JlinkARM::JLINKARM_TIF_SWD);
    arm->jlinkSetSpeedFunc(2000);
    arm->jlinkConnectFunc();
    qDebug()<<arm->jlinkIsConnectedFunc();
    qDebug()<<QString::number(arm->jlinkGetIdFunc(),16);
    // uint32_t cpuId[0x6c]={0};
    // for (int var = 0; var < 0x6c; ++var) {
    //     arm->jlinkReadMemFunc(0x40048054+var,4,cpuId+var);
    // }
    // qDebug()<<QByteArray((char*)cpuId,0x6c*4).toHex(' ')
    QFile file("./e.bin");
    qDebug()<<file.open(QFile::ReadOnly);
    burnFileContent = file.readAll();
    //arm->jlinkEraseChipFunc();
    connect(timer,&QTimer::timeout,this,[&](){
            if(burnFileContent.isEmpty())
            {
                timer->stop();
                arm->jlinkResetFunc();
                arm->jlinkClose();
                qDebug()<<"ed";
                return;
            }
            else
            {
                if((uint)burnFileContent.size()>RJLINK_BURN_CONTENT_SIZE)//每次搬运1K数据
                {
                    qDebug()<<arm->jlinkWriteMemFunc(burnAddr,RJLINK_BURN_CONTENT_SIZE,burnFileContent.data());
                    burnAddr+=RJLINK_BURN_CONTENT_SIZE;
                    burnFileContent.remove(0,RJLINK_BURN_CONTENT_SIZE);
                }
                else
                {
                    qDebug()<<arm->jlinkWriteMemFunc(burnAddr,burnFileContent.size(),burnFileContent.data());
                    burnAddr+=burnFileContent.size();
                    burnFileContent.clear();
                }
            }
        qDebug()<< burnFileContent.size();
    });
    timer->start(1);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_fwFilePathSelectPushButton_clicked()
{

}

